/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
/*
 * This copy of Woodstox XML processor is licensed under the
 * Apache (Software) License, version 2.0 ("the License").
 * See the License for details about distribution rights, and the
 * specific rights regarding derivate works.
 *
 * You may obtain a copy of the License at:
 *
 * http://www.apache.org/licenses/
 *
 * A copy is also included in the downloadable source code package
 * containing Woodstox, in file "ASL2.0", under the same directory
 * as this file.
 */
package com.je.bpm.engine.impl.cmd;

import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Strings;
import com.je.bpm.core.model.BpmnModel;
import com.je.bpm.core.model.FlowElement;
import com.je.bpm.core.model.SequenceFlow;
import com.je.bpm.core.model.task.KaiteBaseUserTask;
import com.je.bpm.engine.ActivitiException;
import com.je.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl;
import com.je.bpm.engine.impl.interceptor.Command;
import com.je.bpm.engine.impl.interceptor.CommandContext;
import com.je.bpm.engine.impl.persistence.entity.TaskEntity;
import com.je.bpm.engine.task.GetTakeNodeNameUtil;

import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 获取正在运行的节点信息
 */
public class GetAllNodeCmd implements Command<List<JSONObject>>, Serializable {

    private static final DateFormat nodeDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

    private String piId;

    public GetAllNodeCmd(String piId) {
        this.piId = piId;
    }


    @Override
    public List<JSONObject> execute(CommandContext commandContext) {
        List<JSONObject> result = new ArrayList<>();
        ProcessEngineConfigurationImpl processEngineConfiguration = commandContext.getProcessEngineConfiguration();
        List<TaskEntity> list = processEngineConfiguration.getTaskDataManager().findTasksByProcessInstanceId(piId);
        Set<String> runNodes = getRunNodes(list);
        String pdid = list.get(0).getProcessDefinitionId();
        BpmnModel bpmnModel = processEngineConfiguration.getRepositoryService().getBpmnModel(pdid);
        Map<String, FlowElement> flowElementMap = bpmnModel.getMainProcess().getFlowElementMap();

        for (String key : flowElementMap.keySet()) {
            JSONObject node = new JSONObject();
            FlowElement flowElement = flowElementMap.get(key);
            if (!(flowElement instanceof KaiteBaseUserTask)) {
                continue;
            }
            KaiteBaseUserTask kaiteBaseUserTask = (KaiteBaseUserTask) flowElement;
            node.put("taskDefinitionKey", kaiteBaseUserTask.getId());
            SequenceFlow sequenceFlow = kaiteBaseUserTask.getIncomingFlows().size() > 0 ? kaiteBaseUserTask.getIncomingFlows().get(0) : null;
            String target = sequenceFlow != null ? sequenceFlow.getId() : "";
            node.put("target", target);
            node.put("taskDefinitionName", Strings.isNullOrEmpty(kaiteBaseUserTask.getName()) ?
                    GetTakeNodeNameUtil.builder().getTakeNodeName(kaiteBaseUserTask.getId()) : kaiteBaseUserTask.getName());
            if (runNodes.contains(kaiteBaseUserTask.getId())) {
                node.put("state", "0");
            } else {
                node.put("state", "1");
            }
            node.put("taskId", list.get(0).getId());
            result.add(node);
        }

        return result;
    }

    private Set<String> getRunNodes(List<TaskEntity> list) {
        if (list.size() == 0) {
            throw new ActivitiException("流程已经结束，请重新打开表单查看！");
        }
        Set<String> set = new HashSet<>();
        for (TaskEntity taskEntity : list) {
            String nodeId = taskEntity.getTaskDefinitionKey();
            if (set.contains(nodeId)) {
                continue;
            }
            set.add(nodeId);
        }
        return set;
    }

}
